package com.millstein.rothn.service.impl;

import cn.hutool.core.util.IdUtil;
import com.millstein.rothn.exception.CustomerException;
import com.millstein.rothn.service.UploadService;
import com.millstein.rothn.util.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

@Service
@Slf4j
public class UploadServiceImpl implements UploadService {

    @Value("${file.upload.location}")
    private String location;

    @Value("${file.server.prefix}")
    private String prefix;

    /**
     * 上传图片
     * @param file 上传的图片数据
     * @return
     */
    @Override
    public String upload(MultipartFile file) {
        if (file == null) {
            throw new CustomerException("上传的图片不存在");
        }
        return this.doUploadItem(file);
    }

    /**
     * 上传单个图片
     * @param multipartFile 图片信息
     * @return
     */
    private String doUploadItem(MultipartFile multipartFile) {
        // 1.处理上传的文件命名
        String fileName = IdUtil.getSnowflake(1, 1).nextId() + ".jpg";

        // 2.进行目录打散，目录结构为`年月日/errid/文件名`
        String year = DateUtil.getCurrentYear();
        String month = DateUtil.getCurrentMonth();
        String day = DateUtil.getCurrentDay();
        String uploadDir = year + "/" + month + "/" + day;
        File dirFile = new File(location, uploadDir);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }

        // 3.创建目标文件
        File destFile = new File(dirFile, fileName);

        // 4.复制文件到服务器
        FileOutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(destFile);
            IOUtils.copy(multipartFile.getInputStream(), outputStream);
            return prefix + uploadDir + "/" + destFile.getName();
        } catch (Exception e) {
            throw new CustomerException("保存文件时发生异常");
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
